package com.demon.auto.utils;

import com.demon.auto.model.dto.UserSecurityDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.UUID;

/**
 * @author huangrz
 * @version 1.0 2025年02月15日
 * @modified huangrz 2025年02月15日
 */
@Slf4j
public class CommonUtil {

    public static String getUuid() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static boolean isNumberString(String str) {
        return str.matches("\\d+");
    }

    public static Long getCurrentUserId() {
        UserSecurityDto user = getCurrentUserInfo();
        if (user == null) {
            throw new RuntimeException("当前用户信息为空！");
        }
        return user.getId();
    }

    public static Long getCurrentUserIdCatch() {
        UserSecurityDto user = getCurrentUserInfo();
        if (user == null) {
            return -1L;
        }
        return user.getId();
    }

    public static String getCurrentUserName() {
        UserSecurityDto user = getCurrentUserInfo();
        if (user == null) {
            throw new RuntimeException("当前用户信息为空！");
        }
        return user.getUsername();
    }

    public static String getCurrentUserEmail() {
        UserSecurityDto user = getCurrentUserInfo();
        if (user == null) {
            throw new RuntimeException("当前用户信息为空！");
        }
        return user.getEmail();
    }

    public static UserSecurityDto getCurrentUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !(authentication.getPrincipal() instanceof UserSecurityDto)) {
            return null;
        }
        return (UserSecurityDto) authentication.getPrincipal();
    }

}
